package com.masblearn;

import java.awt.*;
import java.util.Random;

public class Bullet extends GameObject {
    private static final int SPEED = 10;
    public static int WIDTH = ResourceManager.bulletU.getWidth();
    public static int HEIGHT = ResourceManager.bulletU.getHeight();

    Rectangle rect = new Rectangle();

//    private int x, y;
    private Dir dir;

    private boolean living = true;
    public Group group = Group.BAD;

    public Bullet(int x, int y, Dir dir, Group group) {
        this.x = x;
        this.y = y;
        this.dir = dir;

        this.group = group;

        rect.x = this.x;
        rect.y = this.y;
        rect.width = WIDTH;
        rect.height = HEIGHT;
    }

    public void paint(Graphics g) {
        if (!living) {
            GameModel.getInstance().remove(this);
        }
        switch (dir) {
            case UP:
                g.drawImage(ResourceManager.bulletU, x, y, null);
                break;
            case DOWN:
                g.drawImage(ResourceManager.bulletD, x, y, null);
                break;
            case LEFT:
                g.drawImage(ResourceManager.bulletL, x, y, null);
                break;
            case RIGHT:
                g.drawImage(ResourceManager.bulletR, x, y, null);
                break;
            default:
                break;
        }

        //移动
        move();
    }

    @Override
    public int getWidth() {
        return WIDTH;
    }

    @Override
    public int getHeight() {
        return HEIGHT;
    }

    private void move() {
        switch (dir) {
            case UP:
                y -= SPEED;
                break;
            case DOWN:
                y += SPEED;
                break;
            case LEFT:
                x -= SPEED;
                break;
            case RIGHT:
                x += SPEED;
                break;
            default:
                break;
        }
        //update rect
        rect.x = this.x;
        rect.y = this.y;
        rect.width = WIDTH;
        rect.height = HEIGHT;

        if (x < 0 || y < 0 || x > TankFrame.GAME_WIDTH || y > TankFrame.GAME_HEIGHT) {
            living = false;
        }
    }

    //碰撞检测。判断两个方块是否相交
    public boolean colliedwith(Tank tank) {
        if (this.group == tank.getGroup()) {
            return false;
        }
//        TODO:用一个Rectangle来记录子弹位置。
//        Rectangle rectangle = new Rectangle(this.x, this.y, WIDTH, HEIGHT);
//        Rectangle rectangle1 = new Rectangle(tank.getX(), tank.getY(), tank.TANK_WIDTH, tank.TANK_HEIGHT);
        if (rect.intersects(tank.rectangle)) {
            this.die();
            tank.die();
            GameModel.getInstance().add(new Explode(tank.getX() + tank.TANK_WIDTH / 2 - Explode.Width / 2, tank.getY() + tank.TANK_HEIGHT / 2 - Explode.Heiht / 2));
        }
        return true;
    }

    public void die() {
        this.living = false;
    }
}
